'use strict'

var $ = require('jquery');

var config = {
    serverHost : 'http://43.142.37.148:81/api/'
}

var _common_util = {
    request : function(param){
        var _this = this;
        $.ajax({
            type        : param.method                      || 'get',
            url         : param.url                         || '',
            dataType    : param.type                        || 'json',
            data        : param.data                        || '',
            contentType : param.contentType                 || 'application/x-www-form-urlencoded;charset=UTF-8',
            xhrFields   : { withCredentials: true },
            crossDomain : true,
            success     : function(res){
                if( 0 === res.status) {
                    typeof param.success === 'function' && param.success(res.data, res.msg);
                }
                else if( 10 === res.status){
                    this.doLogin();
                }
                else if(1 === res.status){
                    typeof param.error === 'function' && param.error(res.msg);
                }
            },
            error       : function(err){
                typeof param.error === 'function' && param.error(err.statusText);
            }
        });
    },
    getServerURL : function(path){
        return config.serverHost + path;
    },
    getURLParam : function(name){
        var reg     = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
        var result  = window.location.search.substr(1).match(reg);
        return result ? decodeURIComponent(result[2]) : null;
    },
    // 成功提示
    successTips : function(msg){
        alert(msg || '操作成功！');
    },
    // 错误提示
    errorTips : function(msg){
        alert(msg || '哪里不对了~');
    },
    // 字段的验证，支持非空、手机、邮箱的判断
    validate : function(value, type){
        var value = $.trim(value);
        // 非空验证
        if('require' === type){
            return !!value;
        }
        // 手机号验证
        if('phone' === type){
            return /^1\d{10}$/.test(value);
        }
        // 邮箱格式验证
        if('email' === type){
            return /^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/.test(value);
        }
    },
    doLogin : function(){
        window.location.href = './user-login.html?redirect=' + encodeURIComponent(window.location.href);
    },
    goHome : function(){
        window.location.href = './index.html';
    },
    getQueryVariable : function(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
                var pair = vars[i].split("=");
                if(pair[0] == variable){return pair[1];}
        }
        return(false);
    }
    
};



module.exports = _common_util;